package chapter12.eg2;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class HeartBeatRespHandler extends SimpleChannelInboundHandler<NettyMessage> {

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, NettyMessage message) throws Exception {
    if (message.getHeader() != null
      && message.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()) {
      System.out.println("Receive client heart beat message: --> " + message);
      NettyMessage heartBeat = buildHeartBeat();
      System.out.println("Send heart beat response message to client: --> " + heartBeat);
      ctx.writeAndFlush(heartBeat);
    } else {
      ctx.fireChannelRead(message);
    }
  }

  private NettyMessage buildHeartBeat() {
    NettyMessage message = new NettyMessage();
    Header header = new Header();
    header.setType(MessageType.HEARTBEAT_RESP.value());
    message.setHeader(header);
    return message;
  }
}
